<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\Validate;
use think\facade\Request;
use think\facade\Session;
use app\model\CarModel;
use app\model\Cat2Model;
use app\model\UserModel;
use app\model\DeptModel;
use app\Common;

//货车控制器
class Car{

    //常用数据表内容 及常用字典
    var $CarType=[];
    var $car=[];
    var $users =[];
    var $dept=[];
    var $status=array('1'=>'正常','2'=>'停用');
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";

    public function __construct(){
        //准备一个类型数组

        $gm=new Cat2Model();
        $list = $gm->catTree(1); 
         foreach($list as $k=>$v){
            $this->CarType[$v['id']]=$v;
         }        

        $gm=new CarModel();
        $this->car = $gm->getAll();

        $um=new UserModel();
        $this->users = $um->getAll();
        
        $um=new DeptModel();
        $this->dept = $um->getAll();
       
    }

    public function getImgs($imgs=''){
        if(!$imgs) return '';
        $arr = explode(",",$imgs);
        return implode(",",$arr);
    }

    //car controller index method
    public function index($page=1){
        $uid=Session::get('logonid');
        if(!$uid) return header("location:/index.php/login");             

        $dept = new Dept();
        $my_depts = $dept->getMyDepts($uid); 
        $ar =[];
        foreach($my_depts as $dept){
            $ar[]=$dept['id'];
        }
        $my_depts = implode(",",$ar);

        $list = Db::table('car')->where('dept_id','in',$my_depts);

        $list =$list->order('id')->paginate(20)->toArray();

        foreach($list['data'] as &$v){
            $v['cat_name'] =$this->CarType[$v['cat']]['name'];
            $v['status_name']=$this->status[$v['status']];
            $v['imgs'] = !empty($v['imgs'])? ($v['imgs']):'';
            $v['creater_name'] = $this->users[$v['creater']]['name'];
            $v['trainer_id_name'] = Db::table('customer')->where('id',$v['trainer_id'])->value('name');
            $v['dept_id_name'] = $this->dept[$v['dept_id']]['name'];
        }
        
        //halt($list);
        View::assign(['list'=>$list]);
        return View::fetch();
    }



    //货车编辑
    public function edit(){
        $uid=Session::get('logonid');
        if(!$uid) return header("location:/index.php/login");

        $all = Request::param();
        if(empty($all['id'])) return 'Invalid car id!'.$this->back;        
        $row = Db::table('car')->find($all['id']);
        if(!$row) return 'Invalid car id!'.$this->back ;

        //传入内容,保存数据并跳转
        if(!empty($all['id']) && !empty($all['license'])){
            //检测重复数据
            $ex = Db::query("select * from car where id<>? and license=?",array($all['id'],$all['license']));
            if(count($ex)) {
                return '车牌号['.$all['license'].']已存在!'.$this->back;
            }
            
            //图片
            if($_FILES['file']['size']>0){
                $files =Common::upload();
                if($files['code']){
                    $all['imgs']=$files['msg'];
                }else{
                    return ($files['msg']);
                }

                if($row['imgs']) $del = Common::rm_file($row['imgs']);
            }

            $all['creater'] = 2;
            $all['create_time'] = date('Y-m-d H:i:s');

            $res =Db::table('car')->save($all);
            return header("location:/index.php/car");
        }

        //不传内容只有id,查出本条数据 并进入编辑
        if(empty($row)) $row = Db::table('car')->find($all['id']);

        $dept = new dept();
        $my_depts = $dept->getMyDepts($uid); 
        $ar =[];
        foreach($my_depts as $dept){
            $ar[]=$dept['id'];
        }
        
        $my_depts = implode(",",$ar);        
        $school = Db::table('dept')->where('type',2)->where('status',1)->where('id','in',$my_depts)->select()->toArray();

        $view='edit'.(!empty($all['view'])?$all['view']:'');
        $trainer_list = Db::query('select id,name from customer where status=1 and type=2 and dept_id in (?)',[$my_depts]);
        
        View::assign(['category'=>$this->CarType,'trainer_list'=>$trainer_list,'data'=>$row,'id'=>$row['id'],'school'=>$school]);
        return View::fetch($view);
    }


    public function car_add(){
        $uid=Session::get('logonid');
        if(!$uid) return header("location:/index.php/login/customer_login");

        $all = Request::param();
        if($_POST){
            if(!$all['name']) return '<h1>无效的名称(Invalid car name)!</h1>'.$this->back;;

            $car = new CarModel();
            $row = $car->where('license',$all['license'])->find();
            if(!empty($row)) return '<h1>车牌号['. $all['license']."]已存在！</h1>".$this->back; ;

            $all['creater'] = 2;
            $all['create_time']  = date("Y-m-d H:i:s",time());

            //halt($_FILES);
            if($_FILES['file']['size']>0){
                $files =Common::upload();
                
                if($files['code']){
                    $all['imgs']=$files['msg'];
                }else{
                    return "<h1>".$files['msg']."</h1>".$this->back;
                }
            }
            
            $res = $car->insert($all);
            if($res) {
                return "<h1>教练车新增成功!</h1>".$this->back;
            }
            return "<h1>教练车新增失败!</h1>".$this->back;

            
        }

        $dept = new dept();
        $my_depts = $dept->getMyDepts($uid); 
        $ar =[];
        foreach($my_depts as $dept){
            $ar[]=$dept['id'];
        }
        
        $my_depts = implode(",",$ar);        

        //dump($this->CarType);
        $view='car_add'.(!empty($all['view'])?$all['view']:'');

        $school = Db::table('dept')->where('type',2)->where('status',1)->where('id','in',$my_depts)->select()->toArray();
        View::assign(['category'=>$this->CarType,'school'=>$school]);
        return View::fetch($view);        
    }

    public function cars_near(){
        $uid=Session::get('logonid');
        if(!$uid) return json_encode(['code'=>0,'msg'=>'Access rejected!']);

        $all = Request::param();
        if(empty($all['city'])) return json_encode(['code'=>0,'msg'=>'Access failed!']);

        $list = Db::query("select id,status as s,pos as p from car where city='".$all['city']."'");

        return json_encode(['code'=>1,'data'=>$list,'msg'=>'ok']);
    }



  

}
